import 'dart:math';

import 'package:common_utils/common_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:oktoast/oktoast.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/config/config.dart';
import 'package:yp/helper.dart';
import 'package:yp/pages/mall_app/turntable/state.dart';
import 'package:yp/pages/mall_app/turntable_aword/views/awart_alert.dart';
import 'package:yp/services/api.dart';
import 'package:yp/widgets/bottom_sheet.dart';
import 'package:fluwx/fluwx.dart' as fluwx;

class TurntableLogic extends GetxController {
  final state = TurntableState();
  VoidCallback updateUICallback;

  @override
  void onInit() {
    super.onInit();
    state.source = Get.arguments;
    queryInfo();
    queryAwardList();
    reload();
  }

  reload() {
    check();
    getRemainCount();
  }

  queryInfo() {
    var paramsIntegral = {
      'access_token': SpUtil.getString('token'),
      'usr_num_id': SpUtil.getInt('empeNumId'),
      'turntable_id': state.source['linktarget'],
    };
    Api.queryTurntableData(paramsIntegral).listen((event) {
      if (event['code'] == 0) {
        state.config(event);
      }
      updateUICallback();
    });
  }

  check() {
    var paramsIntegral = {
      'access_token': SpUtil.getString('token'),
      'usr_num_id': SpUtil.getInt('empeNumId'),
      'turntable_id': state.source['linktarget'],
      'draw_dtme': DateUtil.formatDateStr(DateTime.now().toString(),
          format: "yyyyMMddHHmmss"),
      'is_throw_ex': 0,
    };
    Api.turntableCheck(paramsIntegral).listen((event) {
      if (event['code'] == 0) {
        state.power = event;
        if ((state.power['draw_count'] ?? 0) > 0) {
          state.isEnable = true;
        }
        if (event['draw_permission'] == 0) {
          showToast(event['failed_msg']);
          state.isEnable = false;
        }
        print(event);
        updateUICallback();
      }
    });
  }

  draw(Function(bool) callback) async {
    if (!state.isEnable) {
      toast(state.power['failed_msg']);
      return;
    }

    // state.giftNum = Random().nextInt(4);
    // print('--------------------------------');
    // print(state.giftNum);
    // print(
    //     state.bingoRewardFullConfigure[state.giftNum]['reward_level'] ?? '未中奖');
    // print('--------------------------------');
    // callback(true);
    // reload();
    // Future.delayed(Duration(milliseconds: 2500), () {
    //   reload();
    // });

    var paramsIntegral = {
      'access_token': SpUtil.getString('token'),
      'usr_num_id': SpUtil.getInt('empeNumId'),
      'turntable_id': state.source['linktarget'],
      'channel_num_id': 99,
      'draw_dtme': DateUtil.formatDateStr(DateTime.now().toString(),
          format: "yyyyMMddHHmmss"),
    };
    Api.turntableDraw(paramsIntegral).listen((event) {
      if (event['code'] == 0) {
        var data = event['reward_info'];
        state.rewardInfo = data;
        var series = data['series'];
        for (var i = 0; i < state.bingoRewardFullConfigure.length; i++) {
          var e = state.bingoRewardFullConfigure[i];
          if (e['series'] == series) {
            state.giftNum = i;
            break;
          }
        }
        callback(true);
        reload();
      }
    });
  }

  getRemainCount() {
    var paramsIntegral = {
      'access_token': SpUtil.getString('token'),
      'usr_num_id': SpUtil.getInt('empeNumId'),
      'turntable_id': state.source['linktarget'],
      // 'sub_unit_num_id': SpUtil.getInt('storeShopNum'),
      'sub_unit_num_id': SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
    };
    Api.turntableRemainCount(paramsIntegral).listen((event) {
      if (event['code'] == 0) {
        print(event);
        state.remainData = event;
      }
      updateUICallback();
    });
  }

  void queryAwardList() {
    var paramsIntegral = {
      'access_token': SpUtil.getString('token'),
      'usr_num_id': SpUtil.getInt('empeNumId'),
      'turntable_id': state.source['linktarget'],
      'single_usr': 1,
      'ignore_thankyou': 1, //忽略谢谢参与
      'order_type': 1, //  排序类别，0--按最后更新时间倒排，1--按领取状态正排，再按最后更新时间倒排
      'page': 1,
      'rows': 10,
    };
    Api.getTurntableAwardList(paramsIntegral).listen((event) {
      if (event['code'] == 0) {
        state.awardListInfo = event;
      }
      updateUICallback();
    });
  }

  void whetherToSureDialog() {
    showDialog(
        context: Get.context,
        builder: (context) {
          return CupertinoAlertDialog(
            title: Text(
              '提示',
              style:
                  TextStyle(color: Color(0xff222222), fontSize: setWidth(36)),
            ),
            content: Text(
              '确定消耗${state.drawExchangeConfigure['integral_exchange_cost']}积分兑换一次机会',
              style:
                  TextStyle(color: Color(0xff666666), fontSize: setWidth(32)),
            ),
            actions: [
              CupertinoDialogAction(
                child: Text(
                  "取消",
                  style: TextStyle(color: Color(0xff666666)),
                ),
                onPressed: () {
                  Get.back();
                  print("取消");
                },
              ),
              CupertinoDialogAction(
                child: Text("确定"),
                onPressed: () {
                  Get.back();
                  integralToAwardChance();
                },
              ),
            ],
          );
        });
  }

  void integralToAwardChance() {
    var paramsIntegral = {
      'access_token': SpUtil.getString('token'),
      'usr_num_id': SpUtil.getInt('empeNumId'),
      'turntable_id': state.source['linktarget'],
      // 'sub_unit_num_id': SpUtil.getInt('storeShopNum'),
      'sub_unit_num_id': SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
    };
    Api.TurntableIntegralToAward(paramsIntegral).listen((event) {
      if (event['code'] == 0) {
        reload();
      }
    });
  }

  getAwardChance() {
    showDialog(
        context: Get.context,
        builder: (context) {
          return TurntableAwardChanceView(
            data: state.remainData,
            actionEvent: (index) {
              Get.back();
              if (index == 0) {
                whetherToSureDialog();
              } else if (index == 1) {
                //分享
                shareAction();
              } else {
                Get.back();
              }
            },
          );
        });
  }

  shareAction() {
    // 分享弹框
    YpBottomSheet.showShareGift(Get.context, (selectIndex, selectString,
        {info}) async {
      Get.back();
      print(selectIndex.toString() + selectString);
      var model = fluwx.WeChatShareWebPageModel(
        Config.WEB_URL +
            '/activity/pages/turntable/home?turntableId=' +
            state.source['linktarget'] +
            '&shareShopId' +
            SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id']?.toString(),
        title: state.basicInfo['activity_title'],
        thumbnail: fluwx.WeChatImage.network(
            state.basicInfo['activity_share_icon_url']),
        scene: selectIndex == 0
            ? fluwx.WeChatScene.SESSION
            : fluwx.WeChatScene.TIMELINE,
      );
      var result = await fluwx.shareToWeChat(model);
      if (result) {
        reload();
      }
    });
  }
}
